<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <h2 class="title">图书馆管理系统</h2>
        <p class="subtitle">欢迎回来，请登录您的账户</p>
      </div>
      
      <el-form 
        ref="loginForm" 
        :model="form" @submit.prevent="handleLogin" 
        :rules="rules" 
        label-position="top"
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="form.username" 
            placeholder="请输入用户名" 
            size="large"
            prefix-icon="User" 
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="form.password" 
            type="password" 
            placeholder="请输入密码" 
            size="large"
            prefix-icon="Lock" 
            show-password
          />
        </el-form-item>
        
        <div class="form-options">
          <el-checkbox v-model="form.remember">记住密码</el-checkbox>
          <router-link to="/forgot-password" class="forgot-link">忘记密码?</router-link>
        </div>
        
        <el-button 
          type="primary" native-type="submit" 
          size="large"

          :loading="loading" 
          class="login-btn"
        >
          登录
        </el-button>
        
        <div class="register-tip">
          <span>还没有账号?</span>
          <router-link to="/register" class="register-link">立即注册</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const router = useRouter();

// 添加生命周期钩子追踪表单初始化
onMounted(() => {
  console.log('组件已挂载，检查loginForm引用:', loginForm.value);
  if (loginForm.value) {
    console.log('✅ 表单引用在mounted时已初始化');
  } else {
    console.log('❌ 表单引用在mounted时仍未初始化');
  }
});
const loading = ref(false);
const loginForm = ref(null);
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: ['blur', 'submit'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: ['blur', 'submit'] }
  ]
});

const form = ref({ 
  username: localStorage.getItem('rememberedUsername') || '', 
  password: '',
  remember: !!localStorage.getItem('rememberedUsername')
});

const handleLogin = async () => {
    console.log('handleLogin函数已触发，开始处理登录请求');
    console.log('[1/7] 登录按钮被点击，handleLogin函数触发');
    console.log('表单数据初始状态:', form.value);
    console.log('[2/7] 开始登录流程');
  loading.value = true;
  try {
    console.log('[3/7] 开始表单验证');
    // 等待DOM更新完成，确保表单引用已初始化
    await nextTick();
    if (!loginForm.value) {
      console.error('登录表单引用未初始化');
      ElMessage.error('登录表单加载失败，请刷新页面重试');
      return;
    }
    await loginForm.value.validate();
    
console.log('[4/7] 开始发送登录请求到后端:', 'http://localhost:8082/api/auth/login', form.value);
const response = await axios.post('http://localhost:8082/api/auth/login', form.value, { withCredentials: true });
console.log('[5/7] 后端登录请求响应:', response);

    if (response.data) {
      console.log('[6/7] 解析到响应数据，准备存储');
      const { data: user } = response.data;
        if (!user) {
            console.error('登录响应数据不完整: user=', user);
            ElMessage.error('登录失败: 数据不完整');
            return;
          }
          localStorage.setItem('user', JSON.stringify(user));
      
      if (form.value.remember) {
        localStorage.setItem('rememberedUsername', form.value.username);
      } else {
        localStorage.removeItem('rememberedUsername');
      }
      
      ElMessage.success('登录成功');
      console.log('[7/7] 登录成功，准备跳转首页');
      router.push('/home').catch(err => console.error('路由跳转失败:', err));
    }
  } catch (error) {
  
    // 处理表单验证错误
    if (Array.isArray(error) && error.length > 0) {
      const firstError = error[0];
      ElMessage.error(firstError.message || '表单验证失败，请检查输入信息');
      return;
    }
    
    // 处理不同类型错误
    if (!error.response) {
      // 网络错误或无响应
      ElMessage.error('网络连接失败，请检查您的网络设置或稍后重试');
    } else if (error.response.status === 401) {
      // 认证失败
      ElMessage.error('用户名或密码错误，请重新输入');
    } else if (error.response.status === 422) {
      // 表单验证错误
      ElMessage.error('请填写所有必填字段并确保格式正确');
    } else if (error.response.data?.message) {
      // 服务器返回的具体错误
      ElMessage.error(`登录失败: ${error.response.data.message}`);
    } else {
      // 其他未知错误
      ElMessage.error(`登录失败: 服务器错误 (状态码: ${error.response.status})`);
    }
  } finally {
    loading.value = false;
    console.log('🔚 登录流程结束');
  }
};
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 420px;
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08);
  border: none;
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.subtitle {
  font-size: 14px;
  color: #909399;
}

.login-form {
  padding: 0 4px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.forgot-link {
  font-size: 14px;
  color: #409eff;
  text-decoration: none;
}

.login-btn {
  width: 100%;
  margin-bottom: 24px;
}

.register-tip {
  text-align: center;
  font-size: 14px;
  color: #606266;
}

.register-link {
  margin-left: 8px;
  color: #409eff;
  text-decoration: none;
}
</style>